﻿//TODO: check if this implementation is correct.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using System.Drawing;
using System.Drawing.Imaging;

using LowLevelGraphics.ColorSpaces;

namespace LowLevelGraphics.Filter
{
    /// <summary>
    /// Use this to change the color temperature of a pic
    /// For converting a color temperature to RGB, the normal method is to calculate a normalized
    /// spectral power distribution for the blackbody temperature (Me = 1 @ 560nm), 
    /// then convert the spectrum into any color space you desire  
    /// </summary>
    public class ColorTemperature : BaseImageFilter
    {
        protected byte m_nTemperature = 90;

        /// <summary>
        /// default constructor
        /// </summary>
        public ColorTemperature()
        {

        }

        /// <summary>
        /// Used by clone to create a deep copy
        /// </summary>
        /// <param name="_colorTemperature"></param>
        internal ColorTemperature(ColorTemperature _colorTemperature)
        {
            this.m_nTemperature = _colorTemperature.m_nTemperature;
        }

        /// <summary>
        /// Gets or sets the temperature of a picture
        /// </summary>
        public byte Temperature
        {
            get { return m_nTemperature; }
            set { m_nTemperature = value; }
        }

        /// <summary>
        /// Executes this filter
        /// </summary>
        /// <param name="_bitmap"></param>
        /// <returns></returns>
        public override UnsafeBitmap Execute(UnsafeBitmap _bitmap)
        {
            UnsafeBitmap bitmap = _bitmap;

            int nHeight = bitmap.Height;
            int nWidth = bitmap.Width;

            int y = 0;
            int x = 0;

            Color color = Color.Transparent;
            int nGrayValue = -1;

            for (y = 0; y < nHeight; y++)
            {
                for (x = 0; x < nWidth; x++)
                {
                    color = bitmap.GetPixel(x, y);
                    nGrayValue = ColorFunctions.Gray(color);
                    var hslColor = new HSL(Color.FromArgb(nGrayValue * m_nTemperature / 255, 240, 120)); // From SMImage (Seam Carving)
                    //hslColor.H = nGrayValue;
                    bitmap.SetPixel(x, y, hslColor.ToColor());
                }
            }
            return _bitmap;
        }

        /// <summary>
        /// Create a deep copy
        /// </summary>
        /// <returns></returns>
        public override object Clone()
        {
            return new ColorTemperature(this);
        }
    }
}
